package com.project.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("session")
public class SessionController {

    @RequestMapping("info")
    @ResponseBody
    public String getSessionInfo(HttpServletRequest request){
        HttpSession session = request.getSession();
        //在session对象中，为该用户绑定共享数据。
        // 在该用户多次访问服务器时都可使用
        session.setAttribute("name", "tom");
        request.setAttribute("request", "123");
        return session.getId();
    }

    @RequestMapping("sessionObj")
    @ResponseBody
    public String getSessionObj(HttpServletRequest request){
        HttpSession session = request.getSession();
        String info = "共享数据：<br>";
        info += "session范围："+request.getSession().getAttribute("name")+"<br>";
        info += "request范围："+request.getAttribute("reuqest")+"<br>";

        return info;
    }

    @RequestMapping("checkUser")
    @ResponseBody
    public String checkUserCode(HttpServletRequest request,String userCode){
        //得到服务器产生的随机验证码
        String sessionCode = request.getSession().getAttribute("sessionUserCode").toString();

        if(sessionCode.equalsIgnoreCase(userCode)){
            return "验证通过";
        }
        else{
            return "验证码错误";
        }
    }
}
